﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public static class SpriteExtension
{
    private static Dictionary<Sprite, Mesh> meshCaches = new Dictionary<Sprite, Mesh>();

    private static Mesh CreateMesh(this Sprite sprite)
    {
        Mesh mesh = new Mesh();
        Bounds bounds = sprite.bounds;
        mesh.vertices = new Vector3[] { new Vector3(bounds.min.x, bounds.min.y), new Vector3(bounds.min.x, bounds.max.y), new Vector3(bounds.max.x, bounds.max.y), new Vector3(bounds.max.x, bounds.min.y) };
        mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
        Vector2 scale = new Vector2(1f / ((float) sprite.texture.width), 1f / ((float) sprite.texture.height));
        Vector2 vector2 = new Vector2(sprite.rect.x, sprite.rect.y);
        Vector2 vector3 = new Vector2(sprite.rect.x, sprite.rect.yMax);
        Vector2 vector4 = new Vector2(sprite.rect.xMax, sprite.rect.yMax);
        Vector2 vector5 = new Vector2(sprite.rect.xMax, sprite.rect.y);
        vector2.Scale(scale);
        vector3.Scale(scale);
        vector4.Scale(scale);
        vector5.Scale(scale);
        mesh.uv = new Vector2[] { vector2, vector3, vector4, vector5 };
        mesh.colors = new Color[] { Color.white, Color.white, Color.white, Color.white };
        return mesh;
    }

    public static Mesh GetMesh(this Sprite sprite)
    {
        Mesh mesh;
        bool flag = meshCaches.TryGetValue(sprite, out mesh);
        if (mesh == null)
        {
            mesh = sprite.CreateMesh();
            mesh.hideFlags = HideFlags.DontSave;
        }
        if (!flag)
        {
            meshCaches.Add(sprite, mesh);
        }
        return mesh;
    }
}

